package com.ks.core.aop;


import com.ks.core.core.Result;
import com.ks.core.exception.BizExceptionEnum;
import com.ks.core.redis.RedisLock;
import com.ks.core.redis.RequestUtils;
import com.ks.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dengzh
 * @description: 防止api接口重复提交切面
 * @date 2019/7/27
 */
@Aspect
@Component
@Slf4j
@Order(3)
public class RepeatSubmitAspect {

    @Autowired
    RedisLock redisLock;

    /**
     * 注解切点
     *
     * @param noRepeatSubmit
     */
    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
    }


    @Around("pointCut(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        HttpServletRequest request = RequestUtils.getRequest();
        Assert.notNull(request, "request can not null");

        String token = request.getHeader("Authorization");
        String path = request.getServletPath();
        String key = getKey(token, path);
        String clientId = getClientId();

        int lockSeconds = noRepeatSubmit.lockTime();
        boolean isSuccess = redisLock.tryLock(key, clientId, lockSeconds);
        log.info("tryLock key = [{}], clientId = [{}]", key, clientId);

        if (isSuccess) {
            log.info("tryLock success, key = [{}], clientId = [{}]", key, clientId);
            // 获取锁成功
            Object result;

            try {
                // 执行进程
                result = pjp.proceed();
            } finally {
                // 解锁
                redisLock.releaseLock(key, clientId);
                log.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
            }

            return result;

        } else {
            // 获取锁失败，认为是重复提交的请求
            log.info("tryLock fail, key = [{}]", key);
            return Result.fail(BizExceptionEnum.REPEAT_SUBMIT);
        }

    }

    private String getKey(String token, String path) {
        return token + path;
    }

    /**
     * 获取客户端id（使用UUID）
     *
     * @return
     */
    private String getClientId() {
        return StringUtil.getUUID();
    }
}
